Minimum Depth of Binary Tree
Question
What is the minimum depth of a given binary tree?
Example 1
Input:
3
/ \
9 20
/ \
15 7
Output: 2
Solution
- ▭
- ▯
all//Minimum Depth of Binary Tree.py
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def minDepth(self, root):
if root is None:
return 0
elif root.left is None and root.right is None:
return 1
elif root.left is None:
return self.minDepth(root.right) + 1
elif root.right is None:
return self.minDepth(root.left) + 1
else:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
all//Minimum Depth of Binary Tree.py
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def minDepth(self, root):
if root is None:
return 0
elif root.left is None and root.right is None:
return 1
elif root.left is None:
return self.minDepth(root.right) + 1
elif root.right is None:
return self.minDepth(root.left) + 1
else:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1